<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminUser;
use App\Models\AdminOperationLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    /**
     * 获取管理员用户列表
     */
    public function index(Request $request)
    {
        $query = AdminUser::query();

        // 搜索过滤
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('username', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('name', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        // 角色过滤
        if ($request->filled('role')) {
            $query->where('role', $request->role);
        }

        // 状态过滤
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // 排序
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        $users = $query->paginate($request->get('per_page', 15));

        return response()->json([
            'success' => true,
            'data' => $users
        ]);
    }

    /**
     * 创建管理员用户
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string|max:50|unique:admin_users,username',
            'email' => 'required|email|max:100|unique:admin_users,email',
            'name' => 'required|string|max:50',
            'phone' => 'nullable|string|max:20',
            'password' => 'required|string|min:6',
            'role' => 'required|in:super_admin,admin,operator,viewer',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        // 检查权限：只有超级管理员可以创建超级管理员
        if ($request->role === AdminUser::ROLE_SUPER_ADMIN && 
            $request->user()->role !== AdminUser::ROLE_SUPER_ADMIN) {
            return response()->json([
                'success' => false,
                'message' => '权限不足，无法创建超级管理员'
            ], 403);
        }

        $adminUser = AdminUser::create([
            'username' => $request->username,
            'email' => $request->email,
            'name' => $request->name,
            'phone' => $request->phone,
            'password' => $request->password, // 会自动加密
            'role' => $request->role,
            'status' => AdminUser::STATUS_ACTIVE
        ]);

        // 记录操作日志
        AdminOperationLog::create([
            'admin_user_id' => $request->user()->id,
            'action' => 'create_admin_user',
            'description' => '创建管理员用户',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'result' => AdminOperationLog::RESULT_SUCCESS,
            'details' => json_encode([
                'created_user_id' => $adminUser->id,
                'username' => $adminUser->username,
                'role' => $adminUser->role
            ])
        ]);

        return response()->json([
            'success' => true,
            'message' => '管理员用户创建成功',
            'data' => $adminUser
        ], 201);
    }

    /**
     * 获取管理员用户详情
     */
    public function show($id)
    {
        $adminUser = AdminUser::with(['operationLogs', 'createdTenants'])
                             ->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $adminUser
        ]);
    }

    /**
     * 更新管理员用户
     */
    public function update(Request $request, $id)
    {
        $adminUser = AdminUser::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'username' => 'required|string|max:50|unique:admin_users,username,' . $id,
            'email' => 'required|email|max:100|unique:admin_users,email,' . $id,
            'name' => 'required|string|max:50',
            'phone' => 'nullable|string|max:20',
            'role' => 'required|in:super_admin,admin,operator,viewer',
            'status' => 'required|in:active,inactive,locked'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        // 检查权限
        if ($request->role === AdminUser::ROLE_SUPER_ADMIN && 
            $request->user()->role !== AdminUser::ROLE_SUPER_ADMIN) {
            return response()->json([
                'success' => false,
                'message' => '权限不足，无法设置为超级管理员'
            ], 403);
        }

        // 不能修改自己的角色和状态
        if ($adminUser->id === $request->user()->id) {
            if ($request->role !== $adminUser->role || $request->status !== $adminUser->status) {
                return response()->json([
                    'success' => false,
                    'message' => '不能修改自己的角色和状态'
                ], 400);
            }
        }

        $oldData = $adminUser->toArray();
        $adminUser->update($request->only(['username', 'email', 'name', 'phone', 'role', 'status']));

        // 记录操作日志
        AdminOperationLog::create([
            'admin_user_id' => $request->user()->id,
            'action' => 'update_admin_user',
            'description' => '更新管理员用户',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'result' => AdminOperationLog::RESULT_SUCCESS,
            'details' => json_encode([
                'updated_user_id' => $adminUser->id,
                'username' => $adminUser->username,
                'changes' => array_diff_assoc($request->only(['username', 'email', 'name', 'phone', 'role', 'status']), $oldData)
            ])
        ]);

        return response()->json([
            'success' => true,
            'message' => '管理员用户更新成功',
            'data' => $adminUser
        ]);
    }

    /**
     * 删除管理员用户
     */
    public function destroy(Request $request, $id)
    {
        $adminUser = AdminUser::findOrFail($id);

        // 不能删除自己
        if ($adminUser->id === $request->user()->id) {
            return response()->json([
                'success' => false,
                'message' => '不能删除自己的账号'
            ], 400);
        }

        // 不能删除超级管理员（除非自己也是超级管理员）
        if ($adminUser->role === AdminUser::ROLE_SUPER_ADMIN && 
            $request->user()->role !== AdminUser::ROLE_SUPER_ADMIN) {
            return response()->json([
                'success' => false,
                'message' => '权限不足，无法删除超级管理员'
            ], 403);
        }

        $adminUser->delete();

        // 记录操作日志
        AdminOperationLog::create([
            'admin_user_id' => $request->user()->id,
            'action' => 'delete_admin_user',
            'description' => '删除管理员用户',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'result' => AdminOperationLog::RESULT_SUCCESS,
            'details' => json_encode([
                'deleted_user_id' => $adminUser->id,
                'username' => $adminUser->username,
                'role' => $adminUser->role
            ])
        ]);

        return response()->json([
            'success' => true,
            'message' => '管理员用户删除成功'
        ]);
    }

    /**
     * 重置用户密码
     */
    public function resetPassword(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'new_password' => 'required|string|min:6'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $adminUser = AdminUser::findOrFail($id);
        $adminUser->password = $request->new_password;
        $adminUser->save();

        // 记录操作日志
        AdminOperationLog::create([
            'admin_user_id' => $request->user()->id,
            'action' => 'reset_password',
            'description' => '重置管理员密码',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'result' => AdminOperationLog::RESULT_SUCCESS,
            'details' => json_encode([
                'target_user_id' => $adminUser->id,
                'username' => $adminUser->username
            ])
        ]);

        return response()->json([
            'success' => true,
            'message' => '密码重置成功'
        ]);
    }
}